import {GameEvent} from "db://assets/script/game-event";
import {director} from "cc";
import Long from "long";
import {AssetCoreChange} from "db://assets/script/common/events/asset-events/asset-core-change";
import {AssetId} from "db://assets/proto/shared/v1/props";
import {playerConfigsLoader} from "db://assets/script/configs/player-configs-loader";
import {UserLevelUpEvent} from "db://assets/script/common/events/asset-events/user-level-up-event";
import {lobby} from "db://assets/script/lobby";


export class UserAssetInfo {
    assets: { [k: number]: Long } = {}

    private _actionCallback: Map<string, (body: Uint8Array) => void> = new Map();

    start() {
        this.onActionEvent()
        this.onRequestEvent()
        this.onDataChangeEvent()
    }

    // action为操作类的请求，请求仅发起，返回值仅有基础的资产校验相关，具体操作结果通过ws返回
    // action不会变更本地数据，数据变更需要等到ws返回后进行
    onActionEvent() {
    }

    onRequestEvent() {

    }

    offRequestEvent() {

    }


    offActionEvent() {

    }

    onDataChangeEvent() {
        director.on(GameEvent.assetCoreChange, this._assetCoreChange, this)
    }

    offDataChangeEvent() {
        director.off(GameEvent.assetCoreChange, this._assetCoreChange, this)
    }

    private _assetCoreChange(event: AssetCoreChange) {
        for (let pk in event.assets) {
            if (Number(pk) == AssetId.asset_id_exp && this.assets[pk]) {

                const exp = this.assets[pk]
                const incrExp = event.assets[pk]
                const before = playerConfigsLoader.findPlayerLevelByExp(exp)
                const after = playerConfigsLoader.findPlayerLevelByExp(exp.add(incrExp))
                if (before != after) {
                    director.emit(GameEvent.userLevelUp, new UserLevelUpEvent(before, after))
                    lobby.instance.showToast('宗门威望等级提升！' + before + '级 => ' + after + '级')
                }
            }
            if (this.assets[pk]) {
                this.assets[pk] = this.assets[pk].add(event.assets[pk])
            } else {
                this.assets[pk] = event.assets[pk]
            }
        }
        director.emit(GameEvent.assetCoreChangeComplete, event.assets)
    }


    protected onDestroy(): void {
        this.offActionEvent()
        this.offRequestEvent()
        this.offDataChangeEvent()
    }


}

